<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\token\driver\Redis;
use App\Libs\httpUtil;
use App\Models\User;
use think\Db;
use think\Request;
use OSS\OssClient;
use OSS\Core\OssException;

/**
 * 首页接口
 */
class NewLogin extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }

    /*
    * 注册
    */
    public function login()
    {
        $m_userhome = Db::name("userhome");
        $loginService = new Login();

        $request = Request::instance();
        $loginType = $request->param("loginType");
        $phone = $request->param("phone");
        $password = $request->param("password");
        $code = $request->param("code");
        $openid = $request->param("openid");
        $unionid = $request->param("unionid");
        $inviteCode = $request->param("inviteCode");
        $nickname = $request->param("nickname");
        $avatar = $request->param("avatar");
        $registerType = $request->param("registerType");
        $isApp = $request->param("isApp");

//        $num = $m_userhome->where(['phone'=>$phone])->count();
//        if($num){
//            $this->error("该手机号已被注册");
//        }
        if ($loginType == "PHONEPS") {
            //账号密码登录，不允许注册
            if (empty($phone) || empty($password)) {
                $this->error("账号密码不可为空");
            }
            $user = $m_userhome->field("id,password,avatar,nickname,token,phone,is_suosi_switch,is_renzheng,is_zhuxiao_switch,inviteCode,isVip,loginDay")->where(['phone' => $phone])->find();
            if (empty($user)) {
                $this->error("账号不存在");
            }
            if (md5($password) != $user['password']) {
                $this->error("密码错误");
            }
        } else if ($loginType == "PHONECD") {
            if ($registerType != "XCX") {
                if (empty($phone) || empty($code)) {
                    $this->error("手机号验证码不可为空");
                }
                #验证验证码
                $this->if_code();
            } else {
                if (empty($phone)) {
                    $this->error("手机号不可为空");
                }
            }
            $user = $m_userhome->field("id,password,avatar,nickname,token,phone,is_suosi_switch,is_renzheng,is_zhuxiao_switch,inviteCode,wxopenid,isVip,loginDay")->where(['phone' => $phone])->find();
            Db::name("test_log")->insert(['content' => $phone]);
            if (!$user) {
                Db::name("test_log")->insert(['content' => "未进入"]);
                $this->register($loginService, $phone, $inviteCode, $nickname, $avatar, $registerType, $unionid, $openid, $password);
                $user = $m_userhome->field("id,password,avatar,nickname,token,phone,is_suosi_switch,is_renzheng,is_zhuxiao_switch,inviteCode,isVip,loginDay")->where(['phone' => $phone])->find();
            } else {
                Db::name("test_log")->insert(['content' => "已进入"]);
                Db::name("test_log")->insert(['content' => $registerType]);
                Db::name("test_log")->insert(['content' => "openid:" . $openid]);
                Db::name("test_log")->insert(['content' => "unionid:" . $unionid]);
                if (!empty($registerType)) {
                    if ($registerType == "XCX") {
                        if (empty($user['wxopenid'])) {
                            $m_userhome->where('id', $user['id'])->update(['wxopenid' => $unionid, 'appletOpenid' => $openid]);
                        } else {
                            $this->error("手机号已被注册", '', "230");
                        }
                    } else {
                        if ($registerType == "PCWX") {
                            if (empty($user['wxopenid'])) {
                                $m_userhome->where('id', $user['id'])->update(['wxopenid' => $unionid, 'pcOpenid' => $openid]);
                            } else {
                                $this->error("手机号已被注册", '', "230");
                            }
                        } else {
                            if ($registerType == "APPWX") {
                                if (empty($user['wxopenid'])) {
                                    $m_userhome->where('id', $user['id'])->update(['wxopenid' => $unionid, 'appOpenid' => $openid]);
                                } else {
                                    $this->error("手机号已被注册", '', "230");
                                }
                            } else {
                                if ($registerType == "QQ") {
                                    if (empty($user['qqopenid'])) {
                                        $m_userhome->where('id', $user['id'])->update(['qqopenid' => $openid]);
                                    } else {
                                        $this->error("手机号已被注册", '', "230");
                                    }
                                } else {
                                    if ($registerType == "ZFB") {
                                        if (empty($user['zfbopenid'])) {
                                            $m_userhome->where('id', $user['id'])->update(['zfbopenid' => $openid]);
                                        } else {
                                            $this->error("手机号已被注册", '', "230");
                                        }
                                    } else {
                                        $this->error("手机号已被注册", '', "230");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } else if ($loginType == "XCX") {
            if (empty($openid) || empty($unionid)) {
                $this->error("openid或unionid不可为空");
            }
            $user = $m_userhome->field("id,password,avatar,nickname,token,phone,is_suosi_switch,is_renzheng,is_zhuxiao_switch,inviteCode,isVip,loginDay")->where(['wxopenid' => $unionid])->find();
            if (empty($user)) {
                $user = $m_userhome->field("id,avatar,nickname,token,is_suosi_switch,is_renzheng,phone,is_zhuxiao_switch,inviteCode,isVip,loginDay")->where('xcxopenid', $openid)->find();
                if (empty($user)) {
                    $this->error("账号不存在", '', "209");
                }
            }
            $m_userhome->where('id', $user['id'])->update(['wxopenid' => $unionid, 'appletOpenid' => $openid]);
        } else if ($loginType == "APPWX") {
            if (empty($openid) || empty($unionid)) {
                $this->error("openid或unionid不可为空");
            }
            $user = $m_userhome->field("id,password,avatar,nickname,token,phone,is_suosi_switch,is_renzheng,is_zhuxiao_switch,inviteCode,isVip,loginDay")->where(['wxopenid' => $unionid])->find();
            if (empty($user)) {
                $user = $m_userhome->field("id,avatar,nickname,token,is_suosi_switch,is_renzheng,phone,is_zhuxiao_switch,inviteCode,isVip,loginDay")->where('wxopenid', $openid)->find();
                if (empty($user)) {
                    $this->error("账号不存在", '', "209");
                }
            }
            $m_userhome->where('id', $user['id'])->update(['wxopenid' => $unionid, 'appOpenid' => $openid]);
        } else if ($loginType == "PCWX") {
            if (empty($openid) || empty($unionid)) {
                $this->error("openid或unionid不可为空");
            }
            $user = $m_userhome->field("id,password,avatar,nickname,token,phone,is_suosi_switch,is_renzheng,is_zhuxiao_switch,inviteCode,isVip,loginDay")->where(['wxopenid' => $unionid])->find();
            if (empty($user)) {
                $user = $m_userhome->field("id,avatar,nickname,token,is_suosi_switch,is_renzheng,phone,is_zhuxiao_switch,inviteCode,isVip,loginDay")->where('wxopenid', $openid)->find();
                if (empty($user)) {
                    $this->error("账号不存在", '', "209");
                }
            }
            $m_userhome->where('id', $user['id'])->update(['wxopenid' => $unionid, 'pcOpenid' => $openid]);
        } else if ($loginType == "QQ") {
            $user = $m_userhome->field("id,password,avatar,nickname,token,phone,is_suosi_switch,is_renzheng,is_zhuxiao_switch,inviteCode,isVip,loginDay")->where(['qqopenid' => $openid])->find();
            if (empty($user)) {
                $this->error("账号不存在", '', "209");
            }
        } else if ($loginType == "ZFB") {
            $user = $m_userhome->field("id,password,avatar,nickname,token,phone,is_suosi_switch,is_renzheng,is_zhuxiao_switch,inviteCode,isVip,loginDay")->where(['zfbopenid' => $openid])->find();
            if (empty($user)) {
                $this->error("账号不存在", '', "209");
            }
        } else {
            $this->error("不存在的登录方式");
        }
        if (empty($user)) {
            $this->error("账号不存在");
        }
        if ($user['is_suosi_switch'] == 1) {
            $this->error("账号已禁用");
        }

        if ($user['is_zhuxiao_switch'] == 1) {
            $this->error("您的账号已注销，暂时无法登录，请联系客服处理，联系电话0755-2690489");
        }
        if (!$user['inviteCode']) {
            #创建邀请码
            $newInviteCode = date('YmdHis') . rand(0, 9) . rand(0, 9);
            $yq_image = $loginService->create_image($newInviteCode);
            $yq_data['inviteCode'] = $newInviteCode;
            $yq_data['invite_image'] = $yq_image;
            $m_userhome->where(['id' => $user['id']])->update($yq_data);
            $user['inviteCode'] = $newInviteCode;
            $user['invite_image'] = $yq_image;
        }
        if ($isApp) {
            $s_data['isApp'] = 1;
        }
        #修改token
        $s_data['token'] = md5(time() . rand(100, 999));
        $m_userhome->where(['id' => $user['id']])->update($s_data);
        $user['avatar'] = $loginService->image_url($user['avatar']);
        $user['token'] = $s_data['token'];
        $status = Db::name("userstore")->where("userhome_id = {$user['id']}")->value("status");
        if (!$status) {
            $status = 0;
        }
        if($user['loginDay'] != date("Y-m-d")){
            Db::name("userhome")->where("id = {$user['id']}")->update(['loginDay'=>date("Y-m-d")]);
            $userStatistics = Db::name("user_statistics")->where('createDay', date("Y-m-d"))->where('type', 0)->find();
            if ($userStatistics) {
                Db::name("user_statistics")->where('createDay', date("Y-m-d"))->where('type', 0)->setInc('num', 1);
            } else {
                Db::name("user_statistics")->insert([
                    'num' => 1,
                    'type' => 0,
                    'createDay'=>date("Y-m-d")
                ]);
            }
        }
        $user['status'] = $status;
        $this->success("成功", $user, '200');

    }

    private function register($loginService, $phone, $inviteCode, $nickname, $avatar, $registerType, $unionid, $openid, $password)
    {
        $m_userhome = Db::name("userhome");
        $m_userphone = Db::name("userphone");
        $m_usergroup = Db::name("usergroup");
        $m_userrelation = Db::name("user_relation");
        $m_user_invite_num = Db::name("user_invite_num");
        //开启事务
        Db::startTrans();
        #创建用户
        $add_data['password'] = md5($password);
        $add_data['nickname'] = $nickname ? $nickname : mb_substr($phone, 0, 3) . '*****' . mb_substr($phone, 8, 3);
        $add_data['phone'] = $phone;
        $add_data['avatar'] = $avatar ? $avatar : "/uploads/moren/moren.jpg";
        $add_data['is_renzheng'] = 1;
        $add_data['createtime'] = time();
        $add_data['token'] = md5(time() . rand(1, 10000));
        if ($registerType == "XCX") {
            $add_data['wxopenid'] = $unionid;
            $add_data['appletOpenid'] = $openid;
        } else if ($registerType == "APPWX") {
            $add_data['wxopenid'] = $unionid;
            $add_data['appOpenid'] = $openid;
        } else if ($registerType == "PCWX") {
            $add_data['wxopenid'] = $unionid;
            $add_data['pcOpenid'] = $openid;
        } else if ($registerType == "QQ") {
            $add_data['qqopenid'] = $openid;
        } else if ($registerType == "ZFB") {
            $add_data['zfbopenid'] = $openid;
        }
        $teamUserPhone = null;
        $result = $m_userhome->insertGetId($add_data);
        $inviteUserId = null;
        $teamUserId = null;
        if (isset($inviteCode) && !empty($inviteCode) && $inviteCode) {
            $inviteUser = $m_userhome->where('inviteCode', $inviteCode)->find();
            if ($inviteUser) {
                $inviteUserId = $inviteUser['id'];
                $add_data['inviteUserId'] = $inviteUserId;
                $teamUserId = $loginService->setUserInvite($result, $inviteUserId);
            }
        }
        $loginService->setUserInviteNum($result, $inviteUserId);
        #创建邀请码
        $newInviteCode = date('YmdHis') . rand(0, 9) . rand(0, 9);
        $yq_image = $loginService->create_image($newInviteCode);
        $yq_map['id'] = $result;
        $yq_data['invite_image'] = $yq_image;
        $yq_data['inviteCode'] = $newInviteCode;
        $yq_data['inviteUserId'] = $inviteUserId;
        $yq_data['teamUserId'] = $teamUserId;
        $m_userhome->where($yq_map)->update($yq_data);
        #返回用户信息
        $user_data['id'] = $result;
        $user_data['avatar'] = path($add_data['avatar']);
        $user_data['nickname'] = $add_data['nickname'];
        $user_data['phone'] = $add_data['phone'];
        $user_data['token'] = $add_data['token'];
        $userStatistics = Db::name("user_statistics")->where('createDay', date("Y-m-d"))->where('type', 1)->find();
        if ($userStatistics) {
            Db::name("user_statistics")->where('createDay', date("Y-m-d"))->where('type', 1)->setInc('num', 1);
        } else {
            Db::name("user_statistics")->insert([
                'num' => 1,
                'type' => 1,
                'createDay'=>date("Y-m-d")
            ]);
        }

//        require_once "./huanxin/Easemob.class.php";
//        $e = new \Easemob();
//        #注册环信
//        $e->createUser($result, "123456", $add_data['nickname']);
//        #设置属性  头像、昵称
//        $e->editUser($result, $add_data['nickname'], $user_data['avatar']);
//
//        if (!empty($p_data)) {
//            #查询上级是否有群,有则拉入营销群
//            $group_map['userhome_id'] = $p_data['userhome_id'];
//            $group_map['type'] = '1';
//            $group_data = $m_usergroup->where($group_map)->find();
//
//            $result_u = $e->addGroupMember($group_data['groupnumber'], $result);
//
//            $jinyan_data[] = $result;
//            $e->addGroupJinyan($group_data['groupnumber'], $jinyan_data);
//        }
        Db::commit();
    }


    /*
    * 验证验证码
    */
    public function if_code()
    {
        $m_code = Db::name('code');
        $request = Request::instance();

        $name = $request->param("phone");
        $code = $request->param("code");

        if (empty($name)) {
            $this->error("手机号不能未空");
        }

        if (empty($code)) {
            $this->error("验证码不能为空");
        }
        $map['name'] = $name;
        $map['code'] = $code;
        $map['create_time'] = array('egt', time() - 300);
        $map['status'] = 1;
        $data = $m_code->where($map)->find();
        if (!empty($data)) {
            $s_map['id'] = $data['id'];
            $m_code->where($s_map)->delete();
        } else {
            $this->error("验证码错误", '', '201');
        }
    }

    public function del_user()
    {
        $systemType = config("system.is_test");
        if (!$systemType) {
            $this->success("让我逮到了吧，别在正式用，不然没你好果子吃");
        }
        $request = Request::instance();
        $phone = $request->param("phone");
        Db::name("userhome")->where("phone", $phone)->update(['phone' => $phone . rand(1, 99), 'xcxopenid' => null, 'wxopenid' => null, 'qqopenid' => null, 'zfbopenid' => null]);
        $this->success("成功", 1);
    }

    public function login_wx(Request $request)
    {
        $request = Request::instance();
        $code = $request->param("code");
        if (!$code) {
            $this->error("请传入code");
        }
        //接口地址
        $appId = "wx175ea5edf592c9e5";
        $appSecret = "885bf24f56473ec24598017b82a7b7df";
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appId . "&secret=" . $appSecret . "&code=" . $code . "&grant_type=authorization_code";
        $data = $this->http_get($url);
        if (!$data) {
            $this->error("请求失败");
        }
        $result = json_decode($data, true);
        $this->success($result);
    }

    public function http_get($url)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }


    public function phone()
    {
        $request = Request::instance();
        $sessionKey = $request->param("session_key");
        $encryptedData = $request->param("encryptedData");
        $iv = $request->param("iv");
        include_once "./api/wxsq/wxBizDataCrypt.php";
        $appid = 'wx4a40935421da4a92';
        $pc = new \WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode == 0) {
            $this->success("成功", $data);
        } else {
            $this->error("出现错误", $errCode);
        }
    }
}
